package settings

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)
var Conf=new (AllConfig)

type AllConfig struct {
	*AppConfig		`mapstructure:"app"`
	*LogConfig 		`mapstructure:"log"`
	*MySQLConfig	`mapstructure:"mysql"`
	*RedisConfig	`mapstructure:"redis"`
}

type AppConfig struct {
	Name 				string `mapstructure:"name"`
	Mode 				string `mapstructure:"mode"`
	Version 			string `mapstructure:"version"`
	Port  				int     `mapstructure:"port"`
	StartTime 			string `mapstructure:"start_time"`
	MachineID			int64 `mapstructure:"machine_id"`
	MyAppId 			int  `mapstructure:"myAppId"`
	MyPrivateKey 		string `mapstructure:"myPrivateKey"`
	MyPublicKey 		string `mapstructure:"myPublicKey"`
}

type LogConfig struct {
	Level 		string `mapstructure:"level"`
	FileName 	string `mapstructure:"filename"`
	MaxSize 	int `mapstructure:"max_size"`
	MaxAge 		int `mapstructure:"max_age"`
	MaxBackups  int `mapstructure:"max_backups"`
}

type MySQLConfig struct {
	Host		string  `mapstructure:"host"`
	User  		string `mapstructure:"user"`
	Password 	string `mapstructure:"password"`
	DbName		string `mapstructure:"dbname"`
	Port		int `mapstructure:"port"`
	MaxOpenConns int `mapstructure:"max_open_conns"`
	MaxIdleConns int `mapstructure:"max_idle_conns"`
}

type RedisConfig struct {
	Host		string  `mapstructure:"host"`
	Password 	string `mapstructure:"password"`
	DB			int `mapstructure:"db"`
	Port		int `mapstructure:"port"`
	PoolSize 	int `mapstructure:"pool_size"`
}

func Innit()(err  error) {
	viper.SetConfigFile("config.yaml")
	//viper.SetConfigName("config")// 指定配置文件名称
	//viper.SetConfigType("yaml")//指定配置文件类型
	viper.AddConfigPath(".")
	err=viper.ReadInConfig() //读取配置信息
	if err != nil {
		//读取配置信息失败
		fmt.Printf("viper.ReadInConfig() failed,err:%v\n",err)
		return
	}
	if err:=viper.Unmarshal(&Conf); err!=nil{
		fmt.Printf("viper.Unmarshal failed,err:%v\n",err)
	}
	viper.WatchConfig()
	viper.OnConfigChange(func(in fsnotify.Event) {
		if err:=viper.Unmarshal(Conf); err!=nil{
			fmt.Printf("viper.Unmarshal failed,err:%v\n",err)
		}
	})
	return
}